package com.briup.es.filter;

import com.briup.es.config.exception.ServiceException;
import com.briup.es.config.property.TokenProperty;
import com.briup.es.config.response.Result;
import com.briup.es.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final TokenProperty tokenProperty;
    private final PathMatcher pathMatcher;
    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从请求中获取请求路径
        String path = request.getURI().getPath();
        // 如果请求方式为OPTIONS，或请求路径在白名单中，那么直接放行
        if (isWhitePath(path) || "OPTIONS".equals(request.getMethod().name())) {
            return chain.filter(exchange);
        }

        // 获取请求头中的token，校验token
        String token = request.getHeaders().getFirst(tokenProperty.getHeader());
        try {
            // 校验并解析token，从token中获取用户id
            Integer userId = JwtUtil.fieldValue(token, "userId", Integer.class);
            // 将用户ID添加到请求头，传递给下游服务
            ServerHttpRequest modifiedRequest = request.mutate()
                    .header("X-User-Id", String.valueOf(userId))
                    .build();
            // 继续调用下游服务
            return chain.filter(exchange.mutate().request(modifiedRequest).build());
        } catch (ServiceException e) {
            // 解析失败，可以得到响应数据
            Result<Void> result = Result.fail(e.getCode(), e.getMessage());
            // 将响应数据写入到响应体中
           return writeErrorResponse(response,result);
        } catch (Exception e) {
            return writeErrorResponse(response,Result.fail(e.getMessage()));
        }
    }

    /**
     * 判断本次请求路径是否为白名单路径，如果是那么直接放行
     *
     * @param path 请求的路径
     * @return 判断的结果
     */
    private boolean isWhitePath(String path) {
        List<String> whiteList = tokenProperty.getWhiteList();
        for (String uri : whiteList) {
            // 通过antPathMatcher对两个路径进行对比，符合条件就返回true，不符合继续比较
            if (pathMatcher.match(uri, path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 统一错误响应处理，将异常信息通过json写出到响应体中
     * @param response 响应对象
     * @param result 响应结果集
     * @return 响应数据
     */
    private Mono<Void> writeErrorResponse(ServerHttpResponse response, Result<Void> result) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        try {
            // 将Result对象序列化为JSON字节数组
            byte[] responseBytes = objectMapper.writeValueAsBytes(result);

            // 将JSON数据写入响应体
            DataBuffer buffer = response.bufferFactory().wrap(responseBytes);
            return response.writeWith(Mono.just(buffer));
        } catch (Exception e) {
            // 序列化失败时的回退处理
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
